package com.qys.training.base.util;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CacheUtils {

    private static final Logger logger = LoggerFactory.getLogger(CacheUtils.class);

    @Value("${qys.training.hazelcast.expire-time}")
    private long expireTime;
    @Autowired
    private HazelcastInstance hazelcastInstance;

    public boolean add(String mapName,String key, Object value) {
        IMap<String,Object> map = hazelcastInstance.getMap(mapName);
        map.put(key, value,expireTime,TimeUnit.SECONDS);
        return true;
    }

    public boolean add(String mapName,String key, Object value, long time, TimeUnit unit) {
        IMap<String,Object> map = hazelcastInstance.getMap(mapName);
        map.put(key, value,time,unit);
        return true;
    }


    public void del(String mapName,String... keys) {
        IMap<String,Object> map = hazelcastInstance.getMap(mapName);
        for (String key : keys) {
            map.remove(key);
        }
    }


    public Object get(String mapName,String key) {
        IMap<String,Object> map = hazelcastInstance.getMap(mapName);
        return null == key ? null : map.get(key);
    }
}
